package lee.vioson.remotedata.manager

import android.content.Context
import androidx.datastore.preferences.core.edit
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import lee.vioson.remotedata.bean.AppConfig

/**
 *Author:viosonlee
 *Date:2023/6/10
 *DESCRIPTION:
 */

enum class AppConfigManager {
    INTANCE;

    suspend fun saveInitAppConfig(context: Context, appConfig: AppConfig) {
        context.dataStore.edit {
            it[key_init] = Gson().toJson(appConfig)
        }
    }

    fun getInitAppConfig(context: Context) = flow {
        with(context.dataStore.data.map { it[key_init] }.first()) {
            emit(
                if (this.isNullOrEmpty())
                    null
                else
                    Gson().fromJson(this, AppConfig::class.java)
            )
        }
    }.flowOn(Dispatchers.IO)
}